package com.champrin.replicationofmyblockapix.activity;

import static com.champrin.replicationofmyblockapix.http.HTTPUtils.getStringByStream;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.champrin.replicationofmyblockapix.R;
import com.champrin.replicationofmyblockapix.http.Player;
import com.champrin.replicationofmyblockapix.http.UserResponse;
import com.google.gson.Gson;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class LoginActivity extends AppCompatActivity {
    private EditText editTextUsername;
    private EditText editTextPassword;
    private CheckBox checkBoxAgree;
    private CheckBox checkBoxRemember;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // 初始化界面元素
        editTextUsername = findViewById(R.id.username_login);
        editTextPassword = findViewById(R.id.password_login);
        checkBoxAgree = findViewById(R.id.cb_login);
        checkBoxRemember = findViewById(R.id.cb_save);
        Button buttonRegister = findViewById(R.id.button_register);
        Button buttonLogin = findViewById(R.id.button_login);

        SharedPreferences sharedPreferences = getSharedPreferences(getResources().getString(R.string.save_login_data_file), Context.MODE_PRIVATE);

        String usernameDataKey = getResources().getString(R.string.username_key);
        String passwordDataKey = getResources().getString(R.string.password_key);
        String rememberFlagKey = getResources().getString(R.string.remember_flag);

        if (sharedPreferences.getBoolean(rememberFlagKey, false)) {
            editTextUsername.setText(sharedPreferences.getString(usernameDataKey, ""));
            editTextPassword.setText(sharedPreferences.getString(passwordDataKey, ""));
            checkBoxRemember.setChecked(true);
        }

        // 登录按钮点击事件
        buttonLogin.setOnClickListener(v -> {
            String username = editTextUsername.getText().toString();
            String password = editTextPassword.getText().toString();

            if (username.isEmpty() || password.isEmpty()) {
                Toast.makeText(LoginActivity.this, "请输入用户名和密码", Toast.LENGTH_SHORT).show();
            } else if (!checkBoxAgree.isChecked()) {
                Toast.makeText(LoginActivity.this, "请同意用户协议", Toast.LENGTH_SHORT).show();
            } else {
                login(username, password);
            }
        });

        buttonRegister.setOnClickListener(v -> {
            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            intent.putExtra("message", "register");

            startActivity(intent);
            overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
        });
    }

    // 执行登录逻辑
    private void login(String username, String password) {
        loginResult(username, password);
        if (loginResult != null && loginResult.equals("Success")) {

            // 如果勾选了记住密码，则保存用户名和密码
            saveCredentials(username, password);

            // 登录成功
            Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(LoginActivity.this, MenuActivity.class);
            intent.putExtra("message", "login");
            startActivity(intent);
            overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
        }
    }

    // 保存用户名和密码
    private void saveCredentials(String username, String password) {
        SharedPreferences sharedPreferences = getSharedPreferences(getResources().getString(R.string.save_login_data_file), Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        String usernameDataKey = getResources().getString(R.string.username_key);
        String passwordDataKey = getResources().getString(R.string.password_key);
        String rememberFlagKey = getResources().getString(R.string.remember_flag);

        if (checkBoxRemember.isChecked()) {
            editor.putString(usernameDataKey, username);
            editor.putString(passwordDataKey, password);
            editor.putBoolean(rememberFlagKey, true);
        } else {
            editor.remove(usernameDataKey);
            editor.remove(passwordDataKey);
            editor.remove(rememberFlagKey);

        }
        editor.apply();
    }

    private String loginResult = null;
    private void loginResult(String username, String password) {
        new Thread() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                UserResponse userResponse = null;
                String result = null;
                try {
                    String path = "http://10.33.73.41:8080/login?" + "username=" + username + "&password=" + password;
                    Log.v("d", path);
                    URL url = new URL(path);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(6000);
                    connection.setReadTimeout(6000);
                    //设置请求方式 GET / POST 一定要大小
                    connection.setRequestMethod("GET");
                    connection.setDoInput(true);
                    connection.setDoOutput(false);
                    connection.connect();
                    int responseCode = connection.getResponseCode();
                    if (responseCode != HttpURLConnection.HTTP_OK) {
                        throw new IOException("HTTP error code" + responseCode);
                    }
                    result = getStringByStream(connection.getInputStream());
                    if (result != null) {
                        userResponse = new Gson().fromJson(result, UserResponse.class);
                        Player player = userResponse.getData();
                        if (player != null) {
                            loginResult = userResponse.getMsg();
                            Player.globolPlayer = player;
                            Log.d("d", Player.globolPlayer.toString());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
